
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>javascript实用技巧 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,更短的数组去重写法123[...new Set([2,&quot;12&quot;,2,12,1,2,1,6,12,13,6])]//[2, &quot;12&quot;, 12, 1, 6, 13]//es6的新特性
对象深浅拷贝1.深,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">javascript实用技巧</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                March 23, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/03/23/Js/javascript%E5%AE%9E%E7%94%A8%E6%8A%80%E5%B7%A7/" title="javascript实用技巧" class="">javascript实用技巧</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    46k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    42 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Js/" rel="tag">Js</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="更短的数组去重写法"><a href="#更短的数组去重写法" class="headerlink" title="更短的数组去重写法"></a>更短的数组去重写法</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[...new <span class="built_in">Set</span>([<span class="number">2</span>,<span class="string">"12"</span>,<span class="number">2</span>,<span class="number">12</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">1</span>,<span class="number">6</span>,<span class="number">12</span>,<span class="number">13</span>,<span class="number">6</span>])]</span><br><span class="line"><span class="comment">//[2, "12", 12, 1, 6, 13]</span></span><br><span class="line"><span class="comment">//es6的新特性</span></span><br></pre></td></tr></table></figure>
<h1 id="对象深浅拷贝"><a href="#对象深浅拷贝" class="headerlink" title="对象深浅拷贝"></a>对象深浅拷贝</h1><p>1.深拷贝和浅拷贝只针对像Object, Array这样的引用类型数据。</p>
<p>2.浅拷贝是对对象引用地址进行拷贝，并没有开辟新的栈，也就是拷贝后的结果是两个对象指向同一个引用地址，修改其中一个对象的属性，则另一个对象的属性也会改变。</p>
<p>3.深拷贝则是开启一个新的栈，两个对象对应两个不同的引用地址，修改一个对象的属性，不会改变另一个对象的属性。</p>
<p>浅拷贝<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myInfo=&#123;<span class="attr">name</span>:<span class="string">'守候'</span>,<span class="attr">sex</span>:<span class="string">'男'</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> newInfo=myInfo;</span><br><span class="line"></span><br><span class="line">newInfo.sex=<span class="string">'女'</span>;</span><br><span class="line"><span class="built_in">console</span>.log(myInfo)   <span class="comment">//&#123;name: "守候", sex: "女"&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>假-深拷贝<br>假-深拷贝这个是自己随性命名的，大家看看就好，别当真！<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myInfo=&#123;<span class="attr">name</span>:<span class="string">'守候'</span>,<span class="attr">sex</span>:<span class="string">'男'</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> newInfo=<span class="built_in">Object</span>.assign(&#123;&#125;,myInfo)</span><br><span class="line">newInfo.sex=<span class="string">'女'</span>;</span><br></pre></td></tr></table></figure></p>
<p>真-深拷贝<br>真-深拷贝这个是自己随性命名的，大家看看就好，别当真！<br><a id="more"></a><br>看着深浅拷贝，区别写法很简单，但是那个上面的深拷贝写法是有问题的。看下面案例<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr=[&#123;<span class="attr">a</span>:<span class="number">1</span>,<span class="attr">b</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>,<span class="attr">b</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">var</span> newArr=<span class="built_in">Object</span>.assign([],arr)</span><br><span class="line"><span class="comment">//截断数组</span></span><br><span class="line">newArr.length=<span class="number">1</span></span><br><span class="line"><span class="built_in">console</span>.log(newArr)<span class="comment">//[&#123;a:1,b:2&#125;]</span></span><br><span class="line"><span class="built_in">console</span>.log(arr)<span class="comment">//[&#123;a:1,b:2&#125;,&#123;a:3,b:4&#125;]</span></span><br><span class="line"><span class="comment">//操作newArr，这里看着对arr没影响，实际上已经挖了一个坑，下面就跳进去</span></span><br><span class="line">newArr[<span class="number">0</span>].a=<span class="number">123</span></span><br><span class="line"><span class="comment">//修改newArr[0]这个对象，也是影响了arr[0]这个对象</span></span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">0</span>])<span class="comment">//&#123;a: 123, b: 2&#125;</span></span><br></pre></td></tr></table></figure></p>
<p>//利用递归来实现深拷贝，如果对象属性的值是引用类型（Array,Object），那么对该属性进行深拷贝，直到遍历到属性的值是基本类型为止。 </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">deepClone</span>(<span class="params">obj</span>)</span>&#123;    </span><br><span class="line">  <span class="keyword">if</span>(!obj&amp;&amp; <span class="keyword">typeof</span> obj!== <span class="string">'object'</span>)&#123;      </span><br><span class="line">    <span class="keyword">return</span>;    </span><br><span class="line">  &#125;    </span><br><span class="line">  <span class="keyword">var</span> newObj= obj.constructor === <span class="built_in">Array</span> ? [] : &#123;&#125;;    </span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> obj)&#123;       </span><br><span class="line">    <span class="keyword">if</span>(obj[key])&#123;          </span><br><span class="line">      <span class="keyword">if</span>(obj[key] &amp;&amp; <span class="keyword">typeof</span> obj[key] === <span class="string">'object'</span>)&#123;  </span><br><span class="line">        newObj[key] = obj[key].constructor === <span class="built_in">Array</span> ? [] : &#123;&#125;; </span><br><span class="line">        <span class="comment">//递归</span></span><br><span class="line">        newObj[key] = deepClone(obj[key]);          </span><br><span class="line">      &#125;<span class="keyword">else</span>&#123;            </span><br><span class="line">        newObj[key] = obj[key];         </span><br><span class="line">      &#125;       </span><br><span class="line">    &#125;    </span><br><span class="line">  &#125;    </span><br><span class="line">  <span class="keyword">return</span> newObj; </span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> arr=[&#123;<span class="attr">a</span>:<span class="number">1</span>,<span class="attr">b</span>:<span class="number">2</span>&#125;,&#123;<span class="attr">a</span>:<span class="number">3</span>,<span class="attr">b</span>:<span class="number">4</span>&#125;]</span><br><span class="line"><span class="keyword">var</span> newArr=deepClone(arr)</span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">0</span>])<span class="comment">//&#123;a:1,b:2&#125;</span></span><br><span class="line">newArr[<span class="number">0</span>].a=<span class="number">123</span></span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">0</span>])<span class="comment">//&#123;a:1,b:2&#125;</span></span><br></pre></td></tr></table></figure>
<p>还有一个方法就是简单粗暴法，我现在在用的一个方法！原理很简单，就是先把对象转成字符串，再把字符串转成对象！也能实现同样效果<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> newArr2=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(arr));</span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">0</span>])<span class="comment">//&#123;a:1,b:2&#125;</span></span><br><span class="line">newArr2[<span class="number">0</span>].a=<span class="number">123</span></span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">0</span>])<span class="comment">//&#123;a:1,b:2&#125;</span></span><br><span class="line">上面所说的浅拷贝，真假深拷贝（自己随性命名的），这几种情况，在开发上都有可能要用到，至于要使用哪一种方式，视情况而定！</span><br></pre></td></tr></table></figure></p>
<h1 id="使用事件委托"><a href="#使用事件委托" class="headerlink" title="使用事件委托"></a>使用事件委托</h1><p>一个简单的需求，比如想给ul下面的li加上点击事件，点击哪个li，就显示那个li的innerHTML。这个貌似很简单！代码如下！</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">        &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;ul id=<span class="string">"ul-test"</span>&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">0</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;1&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">2</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;3&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">4</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;5&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">6</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;7&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">8</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;9&lt;/</span>li&gt;</span><br><span class="line">        &lt;<span class="regexp">/ul&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>body&gt;</span><br><span class="line">    &lt;script type=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line">        <span class="keyword">var</span> oUl=<span class="built_in">document</span>.getElementById(<span class="string">"ul-test"</span>);</span><br><span class="line">        <span class="keyword">var</span> oLi=oUl.getElementsByTagName(<span class="string">"li"</span>);</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>,len=oLi.length;i&lt;len;i++)&#123;</span><br><span class="line">            oLi[i].addEventListener(<span class="string">"click"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                alert(<span class="keyword">this</span>.innerHTML)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>html&gt;</span><br></pre></td></tr></table></figure>
<p>很简单，这样就实现了，实际上这里有坑，也待优化！<br>1.for循环，循环的是li，10个li就循环10次，绑定10次事件，100个就循环了100次，绑定100次事件！<br>2.如果li不是本来就在页面上的，是未来元素，是页面加载了，再通过js动态加载进来了，上面的写法是无效的，点击li是没有反应的！<br>所以就者需要用事件委托（即使不考虑上面的第二种情况，也是建议使用事件委托）！代码如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">        &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;ul id=<span class="string">"ul-test"</span>&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">0</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;1&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">2</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;3&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">4</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;5&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">6</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;7&lt;/</span>li&gt;</span><br><span class="line">            &lt;li&gt;<span class="number">8</span>&lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">            &lt;li&gt;9&lt;/</span>li&gt;</span><br><span class="line">        &lt;<span class="regexp">/ul&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>body&gt;</span><br><span class="line">    &lt;script type=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line">        <span class="keyword">var</span> oUl=<span class="built_in">document</span>.getElementById(<span class="string">"ul-test"</span>);</span><br><span class="line">        oUl.addEventListener(<span class="string">"click"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">ev</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">var</span> ev=ev||<span class="built_in">window</span>.event;</span><br><span class="line">            <span class="keyword">var</span> target=ev.target||ev.srcElement;</span><br><span class="line">            <span class="comment">//如果点击的最底层是li元素</span></span><br><span class="line">            <span class="keyword">if</span>(target.tagName.toLowerCase()===<span class="string">'li'</span>)&#123;</span><br><span class="line">                alert(target.innerHTML)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>html&gt;</span><br><span class="line">这样写，即使是动态添加进来的li点击也有反应，还有一个就是ul只有一个，事件绑定在ul上，无论li多少个，都是添加一次事件！但是也是可能会有问题，如果li下面还有子元素，那么点击的时候，target可能不是li，而是鼠标点击那个位置的最底层元素！如下图，如果鼠标点击白色区域，那个target就是body元素,鼠标点击绿色区域target就是div元素，鼠标点击蓝色区域target就是ul，点击橙色就是li。</span><br></pre></td></tr></table></figure>
<h1 id="使用对象作为函数参数"><a href="#使用对象作为函数参数" class="headerlink" title="使用对象作为函数参数"></a>使用对象作为函数参数</h1><p>大家试想下这样一个函数–函数接受几个参数，但是这几个参数都不是必填的，函数该怎么处理？是不是下面这样</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">name,phone,card</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//以上函数，可以任意传参数。比如我想传card等于1472586326。这下是不是这样写</span></span><br><span class="line">personInfo(<span class="string">''</span>,<span class="string">''</span>,<span class="string">'1472586326'</span>)</span><br></pre></td></tr></table></figure>
<p>有没有觉得上面写法奇怪，不太优雅？下面这里看着舒服一点！<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">opt</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line">personInfo(&#123;<span class="attr">card</span>:<span class="string">'1472586326'</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<p>再想一下，如果一个函数，参数很多，怎么处理？<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params">arg1,arg2,arg3,arg4,arg5,arg6,arg7</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>密集恐惧症复发没有复发？下面这样看着会舒服一点！<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">opt</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>最后再想一下，如果需求改了，操作函数也要改！函数也要增加一个参数。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//原来函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">name,phone,card</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//修改后</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">name,age,phone,card</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>这样就是参数修改一次，函数的参数就要修改一次！如果是用对象，就不会出现这样问题！<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//修改前后都是这样，变得是函数的操作内容和调用时候的传参！</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">personInfo</span>(<span class="params">opt</span>)</span>&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看了上面的几个栗子，总结来说，就是当函数的参数不固定的时候，参数多(三个或者三个以上)的时候，建议用一个对象记录参数，这样会比较方便，也为以后如果参数要改留了条后路！</p>
<h1 id="使用push和apply合并数组"><a href="#使用push和apply合并数组" class="headerlink" title="使用push和apply合并数组"></a>使用push和apply合并数组</h1><p>合并数组这个已经是老生常谈的话题了，方法也是多种多样！</p>
<h2 id="concat"><a href="#concat" class="headerlink" title="concat"></a>concat</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr1=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>],arr2=[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line">arr1=arr1.concat(arr2)</span><br><span class="line"><span class="built_in">console</span>.log(arr1)<span class="comment">//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure>
<p>concat会一个全新的数组，表示arr1和arr2两个数组的组合，并让arr1和arr2不变。简单吧？<br>但如果arr1和arr2的长度都很长，那就产生了一个很长很长的数组，内存又被占用了那么多。但是数组长度没限制！</p>
<h2 id="for"><a href="#for" class="headerlink" title="for"></a>for</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr1=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>],arr2=[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>,len=arr2.length;i&lt;len;i++)&#123;</span><br><span class="line">    arr1.push(arr2[i])</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(arr1)<span class="comment">//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure>
<p>这里是往arr1循环添加arr2的元素，但是有一个情况，arr1的长度远小于arr2的长度，是不是循环arr1性能更好，循环次数更少。处理这个很简单，但是万一不知道arr1和arr2到底哪个长度更少呢？而且，for循环不够优雅！（当然，这个可以用迭代方法来替代）</p>
<h2 id="reduce"><a href="#reduce" class="headerlink" title="reduce"></a>reduce</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr1=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>],arr2=[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line">arr1 = arr2.reduce(<span class="function">(<span class="params">fcoll,item</span>) =&gt;</span> &#123;</span><br><span class="line">     coll.push( item );</span><br><span class="line">     <span class="keyword">return</span> coll;</span><br><span class="line"> &#125;, arr1 );</span><br><span class="line"> <span class="built_in">console</span>.log(arr1)<span class="comment">//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure>
<p>逼格高了一点，而且用ES6的箭头函数还可以减少一些代码量，但它仍然需要一个函数，每个元素都需要调用一次。</p>
<h2 id="push-apply"><a href="#push-apply" class="headerlink" title="push.apply"></a>push.apply</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr1=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>],arr2=[<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line">arr1.push.apply(arr1,arr2);</span><br><span class="line"><span class="built_in">console</span>.log(arr1)<span class="comment">//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure>
<p>逼格看着高，代码少，也不会产生新的数组，也不难理解，就是调用arr1.push这个函数实例的apply方法，同时把arr2当作参数传入，这样arr1.push这个方法就会遍历arr2数组的所有元素，达到合并的效果。相当于arr1.push.apply(arr1,[6,7,8,9,10]);，最后相当于arr1.push(6,7,8,9,10)。遗憾的就是，这个方法对数组长度有限制，网上说法是不同浏览器，不同的长度限制，一般不超过10万！</p>
<h1 id="toFixed保留整数"><a href="#toFixed保留整数" class="headerlink" title="toFixed保留整数"></a>toFixed保留整数</h1><p>在开发上，经常会遇到最多保留多少位小数或者类似的问题，针对这个，使用toFixed可以很简单的解决问题，但是如果数据是要和后台交互的，而且后台存储的数据一般是保存数字类型，而使用toFixed后生成的是一个字符串，这下，就需要把toFixed生成的是一个字符串转成数字类型，转发很多。今天我说一个最简单–+。代码如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a=<span class="number">123.36896335</span>.toFixed(<span class="number">2</span>)</span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//'123.37'</span></span><br><span class="line">a=+a</span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//123.37</span></span><br></pre></td></tr></table></figure>
<p>PS：a=a|0和~~a也可以实现，但是生成的是一个整数，如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a=<span class="number">123.36896335</span>.toFixed(<span class="number">2</span>)</span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//'123.37'</span></span><br><span class="line">a=a|<span class="number">0</span>  </span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//123 </span></span><br><span class="line"><span class="comment">//---------------------------------分割线</span></span><br><span class="line"><span class="keyword">var</span> a=<span class="number">123.36896335</span>.toFixed(<span class="number">2</span>)</span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//'123.37'</span></span><br><span class="line">a=~~a  </span><br><span class="line"><span class="built_in">console</span>.log(a)<span class="comment">//123</span></span><br></pre></td></tr></table></figure>
<h1 id="其它类型数据转布尔数据"><a href="#其它类型数据转布尔数据" class="headerlink" title="其它类型数据转布尔数据"></a>其它类型数据转布尔数据</h1><p>下面的转换，大家一看就明白了，不多说。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(!!<span class="string">'123'</span>)</span><br><span class="line"><span class="comment">//true</span></span><br><span class="line">!!<span class="number">12</span></span><br><span class="line"><span class="comment">//true</span></span><br><span class="line">!!<span class="number">-1</span></span><br><span class="line"><span class="comment">//true</span></span><br><span class="line">!![]</span><br><span class="line"><span class="comment">//true</span></span><br><span class="line">!!<span class="string">''</span></span><br><span class="line"><span class="comment">//false</span></span><br><span class="line">!!<span class="literal">null</span></span><br><span class="line"><span class="comment">//false</span></span><br></pre></td></tr></table></figure></p>
<h1 id="缓存变量"><a href="#缓存变量" class="headerlink" title="缓存变量"></a>缓存变量</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>,i&lt;arr.length;i++)&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//------------------------分割线</span></span><br><span class="line"><span class="keyword">var</span> arr=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>]</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>,len=arr.length;i&lt;len;i++)&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第一段就是每一次循环的时候，都要查询一次arr.length。第二段代码就是缓存了arr.length，每次对比len就好，理论上是第二段代码的写法比较好，性能比较高！但是随着浏览器的发展，这个细节的性能上的影响貌似远远小于预期，现在还是建议缓存！我写了下面的测试用例(谷歌浏览器测试)！</p>
<h1 id="元素事件"><a href="#元素事件" class="headerlink" title="元素事件"></a>元素事件</h1><p>这里我用jquery来讲解，比较容易理解，原生js也是这个道理！如下代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">'.div1'</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   ...</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//--------------------------分割线   </span></span><br><span class="line"><span class="keyword">var</span> $div1=$(<span class="string">'.div1'</span>);</span><br><span class="line">$div1.click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">   ...</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>上面的代码，改变的也是缓存了$(‘.div1’)，但是这里就建议是第二种写法了，因为第一种点击一次就要查询一次.div1，Dom的操作还是能减少就减少！</p>
<h1 id="使用innerHTML添加元素"><a href="#使用innerHTML添加元素" class="headerlink" title="使用innerHTML添加元素"></a>使用innerHTML添加元素</h1><p>比如有一个需求，往ul里面添加10个li，两种方法，如下代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">    &lt;head&gt;</span><br><span class="line">        &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">        &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>head&gt;</span><br><span class="line">    &lt;body&gt;</span><br><span class="line">        &lt;ul id=<span class="string">"ul-test"</span>&gt;</span><br><span class="line">            </span><br><span class="line">        &lt;<span class="regexp">/ul&gt;</span></span><br><span class="line"><span class="regexp">    &lt;/</span>body&gt;</span><br><span class="line">    &lt;script type=<span class="string">"text/javascript"</span>&gt;</span><br><span class="line">        <span class="keyword">var</span> oUl=<span class="built_in">document</span>.getElementById(<span class="string">"ul-test"</span>);</span><br><span class="line">        <span class="comment">//createElement方式</span></span><br><span class="line">        <span class="built_in">console</span>.time();</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">            <span class="keyword">var</span> oLi=<span class="built_in">document</span>.createElement(<span class="string">'li'</span>);</span><br><span class="line">            oLi.innerHTML=i;</span><br><span class="line">            oUl.appendChild(oLi);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">console</span>.timeEnd();</span><br><span class="line">        <span class="comment">//innerHTML方式</span></span><br><span class="line">        <span class="built_in">console</span>.time();</span><br><span class="line">        <span class="keyword">var</span> _html=<span class="string">''</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">            _html+=<span class="string">'&lt;li&gt;'</span>+i+<span class="string">'&lt;/li&gt;'</span></span><br><span class="line">        &#125;</span><br><span class="line">        oUl.innerHTML=_html;</span><br><span class="line">        <span class="built_in">console</span>.timeEnd();</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>html&gt;</span><br></pre></td></tr></table></figure>
<p>大家把代码用浏览器打开，发现基本是第二种方式更快，第8点也说了，DOM操作能少就少！第一种要操作10次DOM，第二种只需要操作1次DOM。还有一个就是，这个只是很简单的li,如果是下面的列表呢？用第一种方式，得createElement多少次，innerHTML多少次，appendChild多少次？代码多，各个节点的逻辑和嵌套关系也乱！用第二种方式就是一个拼接字符串的操作，比第一种方式好多了，如果用es6的模板字符串，就更简单了！</p>
<h1 id="将参数转成数组"><a href="#将参数转成数组" class="headerlink" title="将参数转成数组"></a>将参数转成数组</h1><p>函数里的arguments，虽然拥有length属性，但是arguments不是一个数组，是一个类数组，没有push,slice等方法。有些时候，需要把arguments转成数组，转的方法也不止一个，推荐的是是下面的写法！</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> _arguments=<span class="built_in">Array</span>.prototype.slice.apply(<span class="built_in">arguments</span>)</span><br></pre></td></tr></table></figure>
<h1 id="函数节流"><a href="#函数节流" class="headerlink" title="函数节流"></a>函数节流</h1><p>这里拿一个栗子说，比如mousemove,onscroll,onresize这些事件触发的时候，可能已经触发了60次事件，这样很消耗性能，而且实际上，我们并不需要这么频繁的触发，只要大约100毫秒触发一次就好！那么这样就需要函数节流了！<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">``</span><span class="string">`</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">*普通写法*</span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>javascript</span><br><span class="line"><span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">beginCount</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    count++;</span><br><span class="line">    <span class="built_in">console</span>.log(count);</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">document</span>.onmousemove = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">   beginCount();</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p><em>节流写法</em><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">beginCount</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    count++;</span><br><span class="line">    <span class="built_in">console</span>.log(count);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">delayFn</span>(<span class="params">method, thisArg</span>) </span>&#123;</span><br><span class="line">    clearTimeout(method.props);</span><br><span class="line">    method.props = setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        method.call(thisArg)</span><br><span class="line">    &#125;,<span class="number">100</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">document</span>.onmousemove = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    delayFn(beginCount)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p><em>第二种节流方法</em><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">delayFn2</span> (<span class="params">fn, delay, mustDelay</span>)</span>&#123;</span><br><span class="line">     <span class="keyword">var</span> timer = <span class="literal">null</span>;</span><br><span class="line">     <span class="keyword">var</span> t_start;</span><br><span class="line">     <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">         <span class="keyword">var</span> context = <span class="keyword">this</span>, args = <span class="built_in">arguments</span>, t_cur = +<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line">         <span class="comment">//先清理上一次的调用触发（上一次调用触发事件不执行）</span></span><br><span class="line">         clearTimeout(timer);</span><br><span class="line">         <span class="comment">//如果不存触发时间，那么当前的时间就是触发时间</span></span><br><span class="line">         <span class="keyword">if</span>(!t_start)&#123;</span><br><span class="line">             t_start = t_cur;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="comment">//如果当前时间-触发时间大于最大的间隔时间（mustDelay），触发一次函数运行函数</span></span><br><span class="line">         <span class="keyword">if</span>(t_cur - t_start &gt;= mustDelay)&#123;</span><br><span class="line">             fn.apply(context, args);</span><br><span class="line">             t_start = t_cur;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="comment">//否则延迟执行</span></span><br><span class="line">         <span class="keyword">else</span> &#123;</span><br><span class="line">             timer = setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                 fn.apply(context, args);</span><br><span class="line">             &#125;, delay);</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> count=<span class="number">0</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fn1</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    count++;</span><br><span class="line">    <span class="built_in">console</span>.log(count)</span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">//100ms内连续触发的调用，后一个调用会把前一个调用的等待处理掉，但每隔200ms至少执行一次</span></span><br><span class="line"><span class="built_in">document</span>.onmousemove=delayFn2(fn1,<span class="number">100</span>,<span class="number">200</span>)</span><br></pre></td></tr></table></figure></p>
<p><a href="https://segmentfault.com/a/1190000011031658" target="_blank" rel="noopener">原文地址</a></p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#更短的数组去重写法"><span class="toc-number">1.</span> <span class="toc-text">更短的数组去重写法</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#对象深浅拷贝"><span class="toc-number">2.</span> <span class="toc-text">对象深浅拷贝</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用事件委托"><span class="toc-number">3.</span> <span class="toc-text">使用事件委托</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用对象作为函数参数"><span class="toc-number">4.</span> <span class="toc-text">使用对象作为函数参数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用push和apply合并数组"><span class="toc-number">5.</span> <span class="toc-text">使用push和apply合并数组</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#concat"><span class="toc-number">5.1.</span> <span class="toc-text">concat</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#for"><span class="toc-number">5.2.</span> <span class="toc-text">for</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#reduce"><span class="toc-number">5.3.</span> <span class="toc-text">reduce</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#push-apply"><span class="toc-number">5.4.</span> <span class="toc-text">push.apply</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#toFixed保留整数"><span class="toc-number">6.</span> <span class="toc-text">toFixed保留整数</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#其它类型数据转布尔数据"><span class="toc-number">7.</span> <span class="toc-text">其它类型数据转布尔数据</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#缓存变量"><span class="toc-number">8.</span> <span class="toc-text">缓存变量</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#元素事件"><span class="toc-number">9.</span> <span class="toc-text">元素事件</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#使用innerHTML添加元素"><span class="toc-number">10.</span> <span class="toc-text">使用innerHTML添加元素</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#将参数转成数组"><span class="toc-number">11.</span> <span class="toc-text">将参数转成数组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#函数节流"><span class="toc-number">12.</span> <span class="toc-text">函数节流</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
